<template>
  <div class="login-container">
    <div class="login-content">
      <div class="login-header">
        <img src="../assets/logo.svg" alt="Logo" class="logo" />
        <h1>小学口算练习平台</h1>
        <p class="subtitle">提升计算能力，培养数学思维</p>
      </div>

      <div class="login-box">
        <div class="tab-header">
          <span
            :class="['tab-item', activeTab === 'login' ? 'active' : '']"
            @click="activeTab = 'login'"
          >
            登录
          </span>
          <span
            :class="['tab-item', activeTab === 'register' ? 'active' : '']"
            @click="activeTab = 'register'"
          >
            注册
          </span>
        </div>

        <div class="form-container" v-if="activeTab === 'login'">
          <el-form :model="loginForm" :rules="loginRules" ref="loginForm">
            <el-form-item prop="username">
              <el-input
                v-model="loginForm.username"
                placeholder="请输入用户名"
                prefix-icon="el-icon-user"
              >
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="请输入密码"
                prefix-icon="el-icon-lock"
                @keyup.enter.native="handleLogin"
              >
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="handleLogin"
                :loading="loading"
                class="submit-btn"
                :disabled="!loginForm.username || !loginForm.password"
              >
                登录
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <div class="form-container" v-else>
          <el-form
            :model="registerForm"
            :rules="registerRules"
            ref="registerForm"
          >
            <el-form-item prop="username">
              <el-input
                v-model="registerForm.username"
                placeholder="请输入用户名"
                prefix-icon="el-icon-user"
              >
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                v-model="registerForm.password"
                type="password"
                placeholder="请输入密码"
                prefix-icon="el-icon-lock"
              >
              </el-input>
            </el-form-item>
            <el-form-item prop="confirmPassword">
              <el-input
                v-model="registerForm.confirmPassword"
                type="password"
                placeholder="请确认密码"
                prefix-icon="el-icon-lock"
                @keyup.enter.native="handleRegister"
              >
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="handleRegister"
                :loading="loading"
                class="submit-btn"
                :disabled="
                  !registerForm.username ||
                  !registerForm.password ||
                  !registerForm.confirmPassword
                "
              >
                注册
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <div class="login-footer">
        <p>© {{ new Date().getFullYear() }} 小学口算练习平台</p>
      </div>
    </div>
  </div>
</template>

<script>
import http from "@/utils/request";

export default {
  name: "LoginPage",
  data() {
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.registerForm.password) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };

    return {
      activeTab: "login",
      loading: false,
      loginForm: {
        username: "",
        password: "",
      },
      registerForm: {
        username: "",
        password: "",
        confirmPassword: "",
      },
      loginRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 20,
            message: "长度在 3 到 20 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 20,
            message: "长度在 6 到 20 个字符",
            trigger: "blur",
          },
        ],
      },
      registerRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 20,
            message: "长度在 3 到 20 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 20,
            message: "长度在 6 到 20 个字符",
            trigger: "blur",
          },
        ],
        confirmPassword: [
          { required: true, message: "请确认密码", trigger: "blur" },
          { validator: validateConfirmPassword, trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    handleLogin() {
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          try {
            this.loading = true;
            const response = await http.post("/front/login", {
              username: this.loginForm.username,
              password: this.loginForm.password,
            });

            console.log("登录响应:", response); // 添加日志

            // 确保response中包含token
            if (!response || !response.data || !response.data.token) {
              throw new Error("登录响应中未包含token");
            }

            // 登录成功，保存token和用户信息
            const token = response.data.token;
            const user = response.data.user;
            localStorage.setItem("token", token);
            localStorage.setItem("username", user.userName);
            localStorage.setItem("userId", user.userId);

            console.log("保存的token:", localStorage.getItem("token")); // 验证token保存

            this.$message.success("登录成功");
            this.$router.push("/difficulty");
          } catch (error) {
            console.error("登录错误:", error);
            this.$message.error(error.message || "登录失败，请重试");
          } finally {
            this.loading = false;
          }
        }
      });
    },
    handleRegister() {
      this.$refs.registerForm.validate(async (valid) => {
        if (valid) {
          // 前端验证两次密码是否一致
          if (
            this.registerForm.password !== this.registerForm.confirmPassword
          ) {
            this.$message.error("两次输入的密码不一致");
            return;
          }

          try {
            this.loading = true;
            await http.post("/front/register", {
              username: this.registerForm.username,
              password: this.registerForm.password,
              confirmPassword: this.registerForm.confirmPassword, // 添加确认密码字段
            });

            // 注册成功
            this.$message.success("注册成功");
            this.activeTab = "login";
            // 自动填充登录表单
            this.loginForm.username = this.registerForm.username;
            this.loginForm.password = this.registerForm.password;
            // 清空注册表单
            this.registerForm.username = "";
            this.registerForm.password = "";
            this.registerForm.confirmPassword = "";
          } catch (error) {
            console.error("注册错误:", error);
            this.$message.error(error.message);
          } finally {
            this.loading = false;
          }
        }
      });
    },
  },
};
</script>

<style scoped>
.login-container {
  height: 100vh;
  width: 100vw;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(120deg, #e8f3ff 0%, #f5f9ff 100%);
  position: relative;
}

.login-content {
  width: 100%;
  max-width: 400px;
  padding: 0 20px;
  text-align: center;
}

.login-header {
  margin-bottom: 30px;
  color: #2b79ff;
}

.logo {
  width: 64px;
  height: 64px;
  margin-bottom: 16px;
}

.login-header h1 {
  font-size: 24px;
  margin: 0;
  font-weight: 500;
}

.subtitle {
  font-size: 14px;
  margin: 10px 0 0;
  opacity: 0.9;
}

.login-box {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(43, 121, 255, 0.1);
  overflow: hidden;
}

.tab-header {
  display: flex;
  border-bottom: 1px solid #e8f3ff;
}

.tab-item {
  flex: 1;
  padding: 15px 0;
  text-align: center;
  font-size: 14px;
  color: #909399;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
}

.tab-item.active {
  color: #2b79ff;
  font-weight: 500;
}

.tab-item:hover {
  color: #2b79ff;
}

.form-container {
  padding: 30px;
}

.el-input :deep(.el-input__inner) {
  height: 40px;
  line-height: 40px;
  border-radius: 4px;
}

.el-input :deep(.el-input__prefix) {
  left: 10px;
  font-size: 16px;
  color: #909399;
}

.el-input :deep(.el-input__inner) {
  padding-left: 35px;
}

.submit-btn {
  width: 100%;
  height: 40px;
  font-size: 14px;
  border-radius: 4px;
  margin-top: 10px;
  background: #2b79ff;
  border-color: #2b79ff;
}

.submit-btn:hover {
  background: #5094ff;
  border-color: #5094ff;
}

.submit-btn:disabled {
  background: #a0cfff;
  border-color: #a0cfff;
}

.login-footer {
  margin-top: 20px;
  color: #909399;
  font-size: 12px;
}

@media screen and (max-width: 480px) {
  .login-content {
    padding: 0 15px;
  }

  .login-header h1 {
    font-size: 20px;
  }

  .subtitle {
    font-size: 12px;
  }

  .form-container {
    padding: 20px;
  }
}
</style>
